/*
 *  初始化总集
 */
#include <stdio.h>
#include <stdint.h>

#include "sys_inner.h"

#define SYSINIT_INFO(...) fprintf(stdout, "\033[32m[SYSINIT_INFO] %s(%d): \033[0m", __FUNCTION__, __LINE__),fprintf(stdout, __VA_ARGS__)
#define SYSINIT_ERR(...) fprintf(stderr, "\033[31m[SYSINIT_ERR] %s(%d): \033[0m", __FUNCTION__, __LINE__),fprintf(stderr, __VA_ARGS__)

SysInner *gSysInner = NULL;

// ----- 外部方法 -----

int32_t SysInit()
{
    if (!gSysInner)
        gSysInner = new SysInner();
    return 0;
}

int32_t SysDeInit()
{
    if (gSysInner)
    {
        delete gSysInner;
        gSysInner = NULL;
    }
    return 0;
}

const char* SysPlatName()
{
    if (!gSysInner || !gSysInner->platSys)
        return "";
    return gSysInner->platSys->GetPlatName();
}

const char* SysDevName()
{
    if (!gSysInner || !gSysInner->platSys)
        return "";
    return gSysInner->platSys->GetDevName();
}

// ----- 内部方法 -----

SysInner::SysInner()
{
    int32_t ret;

    ret = SysPlatInit();
    if (ret)
        SYSINIT_ERR("SysPlatInit(): failed(%d)\r\n", ret);

    ret = SysHeartInit();
    if (ret)
        SYSINIT_ERR("SysHeartInit(): failed(%d)\r\n", ret);

    ret = SysFlowInit();
    if (ret)
        SYSINIT_ERR("SysFlowInit(): failed(%d)\r\n", ret);
}

SysInner::~SysInner()
{
    int32_t ret;

    ret = SysHeartDeInit();
    if (ret)
        SYSINIT_ERR("SysHeartDeInit(): failed(%d)\r\n", ret);

    ret = SysFlowDeInit();
    if (ret)
        SYSINIT_ERR("SysFlowDeInit(): failed(%d)\r\n", ret);

    ret = SysPlatDeInit();
    if (ret)
        SYSINIT_ERR("SysPlatDeInit(): failed(%d)\r\n", ret);
}

static void SysPlatKeyCallback(void *priv, PlatInputKey key, PlatInputState state)
{
    ;
}

static void SysPlatTouchCallback(void *priv, int32_t x, int32_t y, PlatInputState state)
{
    ;
}

int32_t SysInner::SysPlatInit()
{
    int32_t ret;

    platSys = new PlatSys();
    ret = platSys->SysInit();
    if (ret == 0)
        SYSINIT_INFO("PlatNema: %s, PlatDevice: %s \r\n", platSys->GetPlatName(), platSys->GetDevName());
    else {
        SYSINIT_ERR("platSys->SysInit(): failed(%d)\r\n", ret);
        return -1;
    }

    platInput = new PlatInput();
    platInput->SetKeyCallback(NULL, &SysPlatKeyCallback);
    platInput->SetTouchCallback(NULL, &SysPlatTouchCallback);

    platStorage = new PlatStorage();
    platDisplay = new PlatDisplay();
    return 0;
}

int32_t SysInner::SysPlatDeInit()
{
    int32_t ret;
    delete platDisplay;
    delete platStorage;
    delete platInput;
    ret = platSys->SysDeInit();
    if (ret)
        SYSINIT_ERR("platSys->SysDeInit(): failed(%d)\r\n", ret);
    delete platSys;
    return 0;
}
